package com.attilax.img;

//import java.awt.Image;
//import java.awt.Toolkit;
//import java.awt.datatransfer.DataFlavor;
//import java.awt.datatransfer.Transferable;
//import java.awt.datatransfer.UnsupportedFlavorException;
//import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

//import javax.imageio.ImageIO;
//import javax.swing.ImageIcon;










import java.net.URLDecoder;

import org.apache.commons.io.FileUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.attilax.exception.ExUtil;
import com.attilax.io.PathUtil4android;
//import com.attilax.io.filex;
import com.attilax.lang.Base64;
import com.attilax.util.StreamUtil;
import com.attilax.web.UrlX;

public class imgx4android {

	/**com.attilax.img.imgx.toDataUriBase64
	 * com.attilax.img.imgx4android.toDataUriBase64 
	 * @param args
	 * @throws UnsupportedEncodingException 
	 */
	public static void main(String[] args) throws UnsupportedEncodingException {
		 
		 
		String imageFilePath = "F:\\美国队长2\\美国队长2.jpg";
		imageFilePath="http://localhost:8080/cms/maindir/%E8%A5%BF%E6%B8%B8%E8%AE%B0%E4%B9%8B%E5%A4%A7%E5%9C%A3%E5%BD%92%E6%9D%A5/%E8%A5%BF%E6%B8%B8%E8%AE%B0%E4%B9%8B%E5%A4%A7%E5%9C%A3%E5%BD%92%E6%9D%A5-fanart.jpg";
		imageFilePath=URLDecoder.decode(imageFilePath, "utf8");
		imgx4android imgx = new imgx4android();
	//	System.out.println(imgx.toDataUriBase64(imageFilePath));
		String localpath="f:\\0local";
	//	imgx.save2local(imageFilePath, localpath);

	}
	
	/**http://192.168.2.114:8080/cms/maindir/V%E5%AD%97%E4%BB%87%E6%9D%80%E9%98%9F/poster.jpg
	 * http://192.168.2.114:8080/cms/maindir/V%E5%AD%97%E4%BB%87%E6%9D%80%E9%98%9F/poster.jpg
	 * 根据图片的URL路径来获取网络图片，核心代码如下：
	 */

	public static Bitmap getBitmapFromUrl(String urlx)   {
		try {
			urlx=UrlX.encodeURI(urlx);
			URL url = new URL(urlx);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(7000);
			conn.setRequestMethod("GET");
			int responseCode = conn.getResponseCode();
			if (responseCode == 200) {
				InputStream inputStream = conn.getInputStream();
				Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
				return bitmap;
			}
			throw new RuntimeException("cant get img from getBitmapFromUrl:"+urlx+"   responseCode:"+responseCode);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		 
	}

	/** 保存方法 */
	public void saveBitmap(String imageFilePath_url, String localpath) {

		Bitmap Bitmap1 = getBitmapFromUrl(imageFilePath_url);
		// Log.e(TAG, "保存图片");
		File f = new File(localpath);
		 if (f.exists()) {
		// f.delete();
			 return;
		  }else
		  {
			  PathUtil4android.createAllPath(localpath);
		  }
		try {
			FileOutputStream out = new FileOutputStream(f);
			Bitmap1.compress(Bitmap.CompressFormat.PNG, 90, out);
			out.flush();
			out.close();
			// Log.i(TAG, "已经保存");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}
	 
//	public  String save2local(String imageFilePath,String... pas) 
//	{
//		
//		return save2local(imageFilePath,pas[0],pas[1]);
//	}
	public String save2localHighPerf(String urlx, String localpath,
			String urlHostPart) {

		String imageFileNoPath = PathUtil4android.getPathNohostNoApproot(
				urlx, urlHostPart);
		String sdRoot = new PathUtil4android().getInnerSDCardPath(); // /storage/sdcard
		localpath = localpath.replace("$sd$", sdRoot);
		//
		localpath = localpath + "/" + imageFileNoPath;
		// saveBitmap(imageFilePath,localpath);
		
		File f = new File(localpath);
		 if (f.exists()) {
		// f.delete();
			 return localpath;
		  }else
		  {
			  PathUtil4android.createAllPath(localpath);
		  }

		try {
			urlx = UrlX.encodeURI(urlx);
			URL url = new URL(urlx);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(7000);
			conn.setRequestMethod("GET");
			int responseCode = conn.getResponseCode();
			if (responseCode != 200)
				throw new RuntimeException(
						"cant get img from getBitmapFromUrl:" + urlx
								+ "   responseCode:" + responseCode);
			// if (responseCode == 200) {
			InputStream inputStream = conn.getInputStream();
			// Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
			StreamUtil strx = new StreamUtil();
			FileOutputStream out = new FileOutputStream(localpath);
			strx.convertStream(inputStream, out);
			strx.flushNclose(out);

			return localpath;
			// }

		} catch (Exception e) {
			ExUtil.throwEx(e);

		}

		return localpath;

	}
	public  String save2local(String imageFilePath,String localpath,String urlHostPart)   {
		 
		String imageFileNoPath= PathUtil4android.getPathNohostNoApproot(imageFilePath, urlHostPart);
		String sdRoot=new PathUtil4android().getInnerSDCardPath(); // /storage/sdcard
		localpath=localpath.replace("$sd$", sdRoot);
//			 
			localpath=localpath+"/"+imageFileNoPath;
		saveBitmap(imageFilePath,localpath);
 
		return localpath;
		
		
		
		
	}
		
	public  String toReplaceSdVar(String imageFilePath) {
		String sdRoot=new PathUtil4android().getInnerSDCardPath(); // /storage/sdcard
		imageFilePath=imageFilePath.replace("$sd$", sdRoot);
		
		File f=new File(imageFilePath);
		if(!f.exists())
			throw new RuntimeException(" file not exist:"+imageFilePath);
		return imageFilePath;
	}
	
	/**
	attilax    2016年4月14日  下午6:40:35
	 * @param string
	 * @return
	 */
	public  String toDataUriBase64(String imageFilePath) {
		//imageFilePath="F:\\美国队长2\\美国队长2.jpg";
		//File f=new File(imageFilePath);
	//	System.out.println( f.exists());
		String sdRoot=new PathUtil4android().getInnerSDCardPath(); // /storage/sdcard
		imageFilePath=imageFilePath.replace("$sd$", sdRoot);
		
		File f=new File(imageFilePath);
		if(!f.exists())
			throw new RuntimeException(" file not exist:"+imageFilePath);
		
		byte[] ba=toByteArray(imageFilePath);
		
		String encode = Base64.encode(ba, false);
		return encode;
	}

	public static byte[] toByteArray(String imageFile)  {
		try {
			   Bitmap bm = BitmapFactory.decodeFile(imageFile);  
			//   bm.
	//	BufferedImage img = ImageIO.read(imageFile);
			//   public byte[] Bitmap2Bytes(Bitmap bm) {
				         ByteArrayOutputStream baos = new ByteArrayOutputStream();
				       bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
				        return baos.toByteArray();
				     
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		
	}

	 
 

 

}
